package com.base.web.core.exception;

import com.base.web.core.common.BaseConstant;
import com.base.web.core.common.JsonResult;
import com.base.web.core.util.RequestUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

/**
 * Created with IntelliJ IDEA.
 * Description: 全局异常捕获处理类
 * User: Mario
 * Date: 2018-06-18 14:55
 */
@ControllerAdvice()
public class ExceptionAdvice {

    //日志
    private final static Logger logger = LoggerFactory.getLogger(ExceptionAdvice.class);

    /**
     * 同时处理ajax和页面请求异常
     *
     * @param request
     * @param e
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    public Object exceptionHandler(HttpServletRequest request, Exception e) {
        logger.error(request.getRequestURL() + "异常：{}", e.getMessage());
        if (RequestUtil.isAjax(request)) {
            return JsonResult.fail(e.getMessage());
        } else {
            ModelAndView mv = new ModelAndView();
            mv.addObject("errorMessage", e.getMessage());
            mv.addObject("errorUrl", request.getRequestURL());
            mv.setViewName(BaseConstant.ERROR_VIEW);
            return mv;
        }
    }
}
